package com.bishe.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.bishe.entity.response.R;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 全局异常处理配置文件
 */
@ControllerAdvice
public class ExceptionHandlerConfig {
    /**
     * 自定义异常类处理
     * @param response
     * @param e
     */
    @ExceptionHandler(value = DataException.class)
    private void DataExceptionHandler(HttpServletResponse response, DataException e){
        response.setContentType("text/html; charset = utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(R.error(e.getMessage()).toString());
            writer.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    @ExceptionHandler(NotLoginException.class)
    public void handlerNotLoginException(HttpServletResponse response,NotLoginException nle) {
        response.setContentType("text/html; charset = utf-8");
        PrintWriter writer = null;
        // 不同异常返回不同状态码
        try {
            writer = response.getWriter();
            String message = "";
            if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
                message = "未提供Token";
                writer.write(R.error(message).toString());
                writer.close();
            } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
                message = "未提供有效的Token";
                writer.write(R.error(message).toString());
                writer.close();
            } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
                message = "登录信息已过期，请重新登录";
                writer.write(R.error(message).toString());
                writer.close();
            } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
                message = "您的账户已在另一台设备上登录，如非本人操作，请立即修改密码";
                writer.write(R.error(message).toString());
                writer.close();
            } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
                message = "已被系统强制下线";
                writer.write(R.error(message).toString());
                writer.close();
            } else {
                message = "当前会话未登录";
                writer.write(R.error(message).toString());
                writer.close();
            }
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
